package io.kiki.stack.netty.channelManager;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;

@Slf4j
@Setter
@Getter
public class CreatePoolTask implements Callable<Pool> {
    private final ChannelManagerImpl channelManager;
    private final boolean whetherInitChannel;
    private Url url;
    private int syncCreateNumWhenNotWarmup;

    public CreatePoolTask(ChannelManagerImpl channelManager) {
        this.channelManager = channelManager;
        this.whetherInitChannel = false;
    }

    public CreatePoolTask(ChannelManagerImpl channelManager, Url url) {
        this.channelManager = channelManager;
        this.whetherInitChannel = true;
        this.url = url;
        this.syncCreateNumWhenNotWarmup = 1;
    }

    public CreatePoolTask(ChannelManagerImpl channelManager, Url url, int syncCreateNumWhenNotWarmup) {
        this.channelManager = channelManager;
        this.whetherInitChannel = true;
        this.url = url;
        this.syncCreateNumWhenNotWarmup = syncCreateNumWhenNotWarmup;
    }

    @Override
    public Pool call() throws Exception {
        final Pool pool = new Pool(channelManager.channelSelectStrategy);
        if (whetherInitChannel) {
            try {
                channelManager.doCreatePool(pool, this.url, syncCreateNumWhenNotWarmup);
            } catch (Exception e) {
                pool.removeAllAndTryClose();
                channelManager.poolKeyToRunStateRecordedFutureTaskMap.remove(url.getId());
                throw e;
            }
        }
        return pool;
    }

}
